<?php

namespace App\Http\Controllers\Api\V1;

// use Illuminate\Http\Request;
use App\Http\Requests\Api\ApiRequest as Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Interfaces\OrderService;

use App\Services\Allinpay\Pay;
use App\Services\Allinpay\Responses\Pay as ResponsePay;
use App\Services\Allinpay\Utils\Form;
use App\Exceptions\Api\ApiDoneErrorException;
use App\Exceptions\Api\ApiInputErrorException;
use App\Exceptions\Api\ApiRsaEecryptErrorException;
use App\Exceptions\Api\ApiUserNotLoginErrorException;
use App\Exceptions\Api\ApiValidateErrorException;
use Log;
use App\Models\Order;
use App\Models\OrderGoods;


class PayController extends Controller
{

    /**
     * @api {post} /pay/alipay_pay 支付地址
     * @apiName Pay/alipay_pay
     * @apiGroup Pay
     * @apiDescription 支付地址.
     * @apiParam {Number} order_id   订单id.
     *
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     * //创建支付单处理完成
     * {
     *   "result": "_input_charset=utf-8&notify_url=http%3A%2F%2Fafuyigou.app%2Fapi%2Fpay%2Falipay_notify&out_trade_no=G5274485385081d&partner=2088121657630089&payment_type=1&seller_id=finance%40afuyigou.com&service=mobile.securitypay.pay&subject=asdf&total_fee=10&sign=nOqXjim4RUARWmAT45kFi%2BO0gV8vJc9RuQEuawHET1THeyiehck%2BB008k3v3Qq7QTFI%2FQq6%2F6EN73ghPFDzSjnUesv3o8GDXq94edkZDXxm%2F%2FYXzoK0ybgokMK8M96NDr%2BVm6soAr82mqpxzrlNx4t8xESCc86pV0DDf0Rn6ItE%3D&sign_type=RSA"
     * }
     * @apiErrorExample Error-Response:
     * HTTP/1.1 400
     * //创建支付单处理失败
     * {
     *   "message": "订单id不能为空"
     * }
     */
    public function alipayPay(Request $request)
    {

        /*$order_sn = $request->order_sn;

        if (empty($order_sn)) {

            throw new ApiInputErrorException("订单编号不能为空");
        }//end if()

        $pay_price = Order::where('order_sn', $order_sn)->pluck('pay_price');*/

        $order_id = $request->order_id;

        if (empty($order_id)) {

            throw new ApiInputErrorException("订单id不能为空");
        }//end if()

        $orders = Order::find($order_id);

        $order_sn = $orders->order_sn;

        $pay_price = $orders->pay_price;

        if (empty($pay_price)) {

            throw new ApiInputErrorException("支付价格不能为空且必须大于0");
        }//end if()

        $orderGoods = OrderGoods::where('order_id', $order_id)->get();

        $subject = '';

        $body = '';

        if ($orderGoods->count()>0) {

            foreach ($orderGoods as $key => $goods) {

                $subject.='['.$goods->goods_name.']';

                $body.='['.$goods->goods_pet_name.']';
            }
        }

        // 创建支付单。
        $alipay = app('alipay.mobile');

        $alipay->setOutTradeNo($order_sn);

        $alipay->setTotalFee($pay_price);

        $alipay->setSubject($subject);

        $alipay->setBody($body);

        // 返回签名后的支付参数给支付宝移动端的SDK。
        // return $alipay->getPayPara();
        //Log::info('支付单参数：'.Response()->json(['result'=>$alipay->getPayPara()]));
        return Response()->json(['result'=>$alipay->getPayPara()]);

        // dd($alipay->getPayPara());
    }


    //支付宝服务异步回调
    public function alipayNotify(Request $request,OrderService $orderService){

        Log::debug('Alipay notify get data verification success (mobile).', [

            'out_trade_no' => $request->get('out_trade_no'),

            'trade_no' => $request->get('trade_no')
        ]);

        // 验证请求。
        if (! app('alipay.mobile')->verify()) {

            Log::notice('Alipay notify post data verification fail (mobile).', ['data' => $request->getContent()]);

            return 'fail';
        }

        // 判断通知类型。
        switch ($request->get('trade_status')) {

            case 'TRADE_SUCCESS':

            case 'TRADE_FINISHED':

            $pay_sn = $request->get('out_trade_no');

            $order_pay_id = $orderService->orderPayBack(

                $pay_sn,

                'alipay',

                $request->get('trade_no'),

                $request->get('notify_time'),

                json_encode($request->all())
            );

            if ($order_pay_id){

                return 'success';
            }

            Log::debug('Alipay notify get data verification success (mobile).', [

                'out_trade_no' => $request->get('out_trade_no'),

                'trade_no' => $request->get('trade_no')
            ]);

            break;
        }

        return 'success';
    }


}
